package com.ma.mapper;

import com.ma.model.Role;
import com.ma.model.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * author: MaHX
 * date: 2019/5/27/16:24
 * description:
 **/
@Mapper
@Repository
public interface UserMapper {
    @Select("select * from user where phone=#{phone}")
    User findUserByPhone(@Param("phone") String phone);

    @Select("select * from user where phone=#{phone}")
    @Results({
            @Result(column = "phone", property = "roleList", javaType = List.class, many = @Many(select = "com.ma.mapper.UserMapper.getRoleNameByPhone")),
    })
    User getUserAndRolesByPhone(@Param("phone") String phone);

    @Select("select r.name from user u LEFT JOIN user_role sru on u.id= sru.User_id LEFT JOIN role r on sru.Role_id=r.id where phone=#{phone}")
    Role getRoleNameByPhone(String phone);


    @Insert("insert into user(username,password,phone,gender) values(#{username},#{password},#{phone},#{gender})")
//    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    int insertUser(User user);

    @Update("update user set password=#{password} where phone=#{phone}")
    void updatePasswordByPhone(@Param("phone") String phone,@Param("password") String password);

    @Delete("delete from user where phone = #{phone}")
    int deleteUserByPhone(@Param("phone") String phone);

    /**
     * - property = “adress”, 表示要将返回的查询结果赋值给user的address属性
     * - column = “id” 是指将user表中的id作为com.ma.mapper.AdressMapper.findAdressByUser_id的查询参数
     * - one 表示这是一个一对一的查询
     * - @One(select = “方法全路径) 表示我们调用的方法
     * @param user_id
     * @return
     */
    @Select("select * from user where id =#{id}")
    @Results({
            @Result(property = "adress",column = "id",one = @One(select = "com.ma.mapper.AdressMapper.findAdressByUser_id"))
    })
    User findUserAndAdressByUser_id(@Param("id") String user_id);

    @Select("select * from user where id = #{id}")
    @Results({
            @Result(property = "cars",column = "id",many=@Many(select = "com.ma.mapper.CarMapper.findCarById"))
    })
    User findUserAndCarsById(@Param("id") int id);

    @Update("update user set recentlyLanded=#{recentlyLanded} where username =#{username}")
    void updateRlByUsername(@Param("recentlyLanded") String recentlyLanded,@Param("username") String username);
}
